<template>
    <!-- 划词AI交互浮层 -->
    <teleport to="body" :disabled="false">
        <div v-if="showModeSelector"
             class="fixed inset-0 pointer-events-none"
             style="z-index: 9999;">
            <!-- 模式选择浮层 -->
            <div ref="selectorRef"
                 data-text-selection-ai
                 id="text-selection-ai-popup"
                 class="absolute bg-white dark:bg-gray-800 rounded-lg shadow-xl border-2 border-blue-500 dark:border-blue-400
                        pointer-events-auto transform transition-all duration-200"
                 :style="selectorStyle">
                
                <!-- 浮层标题 -->
                <div class="px-3 py-2 border-b border-gray-100 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <!-- 标题 -->
                        <div class="flex items-center flex-1">
                            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">AI智能分析</span>
                        </div>
                        <button @click="closeModeSelector"
                                class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 ml-2">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- 选中文本预览 -->
                <div class="px-3 py-2 bg-gray-50 dark:bg-gray-700">
                    <p class="text-xs text-gray-600 dark:text-gray-400 mb-1">选中内容：</p>
                    <p class="text-sm text-gray-800 dark:text-gray-200 line-clamp-2">{{ selectedText }}</p>
                </div>

                <!-- 模式选择按钮 -->
                <div class="p-3 space-y-2">
                    <button v-for="mode in modes" 
                            :key="mode.key"
                            @click="selectMode(mode.key)"
                            :disabled="isProcessing"
                            class="w-full flex items-center px-3 py-2 text-sm text-left rounded-md
                                   bg-gray-50 hover:bg-blue-50 dark:bg-gray-700 dark:hover:bg-blue-900
                                   text-gray-700 hover:text-blue-700 dark:text-gray-300 dark:hover:text-blue-300
                                   border border-transparent hover:border-blue-200 dark:hover:border-blue-700
                                   transition-colors duration-150 disabled:opacity-50 disabled:cursor-not-allowed">
                        <span class="mr-2">{{ mode.icon }}</span>
                        <div>
                            <div class="font-medium">{{ mode.title }}</div>
                            <div class="text-xs text-gray-500 dark:text-gray-400">{{ mode.description }}</div>
                        </div>
                    </button>
                </div>

                <!-- 语言选择器 -->
                <div v-if="showLanguageSelector" class="p-3 border-t border-gray-100 dark:border-gray-700">
                    <div class="mb-3">
                        <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">选择翻译语言</h4>

                        <!-- 快速翻译按钮 -->
                        <button @click="quickTranslate"
                                class="w-full mb-3 px-3 py-2 text-sm bg-blue-500 hover:bg-blue-600 text-white rounded-md
                                       transition-colors duration-150">
                            🔄 智能翻译（中英互译）
                        </button>

                        <!-- 自定义语言选择 -->
                        <div class="space-y-2">
                            <div>
                                <label class="block text-xs text-gray-600 dark:text-gray-400 mb-1">源语言（可选）</label>
                                <select v-model="selectedSourceLanguage"
                                        class="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600
                                               rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                                    <option value="">自动检测</option>
                                    <option v-for="lang in languageOptions" :key="lang.code" :value="lang.code">
                                        {{ lang.flag }} {{ lang.name }}
                                    </option>
                                </select>
                            </div>

                            <div>
                                <label class="block text-xs text-gray-600 dark:text-gray-400 mb-1">目标语言 *</label>
                                <select v-model="selectedTargetLanguage"
                                        class="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600
                                               rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                                    <option value="">请选择目标语言</option>
                                    <option v-for="lang in languageOptions" :key="lang.code" :value="lang.code">
                                        {{ lang.flag }} {{ lang.name }}
                                    </option>
                                </select>
                            </div>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="flex space-x-2 mt-3">
                            <button @click="executeTranslation"
                                    :disabled="!selectedTargetLanguage"
                                    class="flex-1 px-3 py-2 text-sm bg-green-500 hover:bg-green-600 disabled:bg-gray-400
                                           text-white rounded-md transition-colors duration-150 disabled:cursor-not-allowed">
                                开始翻译
                            </button>
                            <button @click="closeLanguageSelector"
                                    class="px-3 py-2 text-sm bg-gray-500 hover:bg-gray-600 text-white rounded-md
                                           transition-colors duration-150">
                                取消
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 处理中状态 -->
                <div v-if="isProcessing" class="px-3 py-2 border-t border-gray-100 dark:border-gray-700">
                    <div class="flex items-center text-sm text-blue-600 dark:text-blue-400">
                        <svg class="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        AI正在分析中...
                    </div>
                </div>
            </div>
        </div>
    </teleport>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, inject, getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
import { textSelectionAi } from '@/api/frontend/ai'
import { showMessage } from '@/composables/util'

// 获取路由信息
const route = useRoute()

// 注入AI助手的方法
const openAiAssistant = inject('openAiAssistant', null)
const addMessageToAiAssistant = inject('addMessageToAiAssistant', null)



// 响应式数据
const showModeSelector = ref(false)
const selectedText = ref('')
const isProcessing = ref(false)
const selectorRef = ref(null)
const selectorStyle = ref({})
const clickListenerEnabled = ref(true)

// 模式配置
const modes = reactive([
    {
        key: 'explain',
        title: '解释说明',
        description: '详细解释选中内容的含义',
        icon: '💡'
    },
    {
        key: 'translate',
        title: '智能翻译',
        description: '中英文互译',
        icon: '🌐'
    },
    {
        key: 'summarize',
        title: '内容总结',
        description: '提取要点和核心观点',
        icon: '📝'
    }
])

// 语言选项
const languageOptions = ref([
    { code: 'zh', name: '中文', flag: '🇨🇳' },
    { code: 'en', name: 'English', flag: '🇺🇸' },
    { code: 'ja', name: '日本語', flag: '🇯🇵' },
    { code: 'ko', name: '한국어', flag: '🇰🇷' },
    { code: 'fr', name: 'Français', flag: '🇫🇷' },
    { code: 'de', name: 'Deutsch', flag: '🇩🇪' },
    { code: 'es', name: 'Español', flag: '🇪🇸' },
    { code: 'ru', name: 'Русский', flag: '🇷🇺' }
])

// 翻译语言选择状态
const showLanguageSelector = ref(false)
const selectedSourceLanguage = ref('')
const selectedTargetLanguage = ref('')

// 当前文章ID（从路由获取）
const articleId = ref(null)

// 组件挂载时添加事件监听
onMounted(() => {
    // 延迟一下确保DOM已经渲染完成
    setTimeout(() => {
        // 只在文章内容区域监听
        const articleContent = document.querySelector('.article-content')
        if (articleContent) {
            articleContent.addEventListener('mouseup', handleTextSelection)
        } else {
            // 如果找不到文章内容区域，则在整个文档监听
            document.addEventListener('mouseup', handleTextSelection)
        }

        document.addEventListener('click', handleDocumentClick)

        // 获取当前文章ID
        if (route && route.params.articleId) {
            articleId.value = parseInt(route.params.articleId)
        }
    }, 100)
})

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
    const articleContent = document.querySelector('.article-content')
    if (articleContent) {
        articleContent.removeEventListener('mouseup', handleTextSelection)
    } else {
        document.removeEventListener('mouseup', handleTextSelection)
    }
    document.removeEventListener('click', handleDocumentClick)
})

// 处理文本选择事件
const handleTextSelection = async (event) => {
    // 如果点击在浮层内，不处理
    if (selectorRef.value && selectorRef.value.contains(event.target)) {
        return
    }

    const selection = window.getSelection()
    const text = selection.toString().trim()

    // 如果没有选中文本或文本太短，隐藏浮层
    if (!text || text.length < 2) {
        if (showModeSelector.value) {
            showModeSelector.value = false
        }
        return
    }

    // 如果选中文本太长，限制长度
    if (text.length > 500) {
        showMessage('选中文本过长，请选择较短的内容', 'warning')
        return
    }

    selectedText.value = text
    
    // 计算浮层位置
    const range = selection.getRangeAt(0)
    const rect = range.getBoundingClientRect()
    
    await nextTick()
    
    // 智能定位算法
    const position = calculateOptimalPosition(rect)

    selectorStyle.value = {
        left: `${position.left}px`,
        top: `${position.top}px`,
        width: `${position.width}px`,
        position: 'fixed',
        zIndex: 9999
    }

    // 临时禁用click监听器，避免立即关闭浮层
    clickListenerEnabled.value = false

    showModeSelector.value = true

    // 使用nextTick确保DOM渲染完成后再启用click监听器
    await nextTick()

    // 延迟重新启用click监听器
    setTimeout(() => {
        clickListenerEnabled.value = true
    }, 300)
}

// 处理文档点击事件
const handleDocumentClick = (event) => {
    // 如果click监听器被临时禁用，忽略此次点击
    if (!clickListenerEnabled.value) {
        return
    }

    // 如果点击在浮层外，关闭浮层
    if (showModeSelector.value && selectorRef.value && !selectorRef.value.contains(event.target)) {
        showModeSelector.value = false
        clickListenerEnabled.value = true
    }
}

// 关闭模式选择器
const closeModeSelector = () => {
    showModeSelector.value = false
    showLanguageSelector.value = false
    selectedSourceLanguage.value = ''
    selectedTargetLanguage.value = ''
    clickListenerEnabled.value = true
}

// 选择模式并处理
const selectMode = async (mode) => {
    if (isProcessing.value) return

    // 如果是翻译模式，显示语言选择器
    if (mode === 'translate') {
        showLanguageSelector.value = true
        // 重新计算位置以适应更大的浮层
        await nextTick()
        adjustPositionForLanguageSelector()
        return
    }

    await processAiRequest(mode)
}

// 处理AI请求
const processAiRequest = async (mode, sourceLanguage = '', targetLanguage = '') => {
    if (isProcessing.value) return

    isProcessing.value = true

    try {
        // 构建请求参数
        const requestData = {
            selectedText: selectedText.value,
            mode: mode,
            articleId: articleId.value
        }

        // 如果是翻译模式且指定了语言，添加语言参数
        if (mode === 'translate') {
            if (sourceLanguage) requestData.sourceLanguage = sourceLanguage
            if (targetLanguage) requestData.targetLanguage = targetLanguage
        }

        // 调用划词AI接口
        const response = await textSelectionAi(requestData)
        
        if (response.success) {
            const { reply, conversationId } = response.data
            
            // 如果有AI助手注入方法，将结果发送到AI助手
            if (openAiAssistant && addMessageToAiAssistant) {
                // 打开AI助手
                openAiAssistant()

                // 添加用户消息和AI回复到聊天记录
                await nextTick()
                addMessageToAiAssistant({
                    userMessage: `【${getModeTitle(mode)}】${selectedText.value}`,
                    aiReply: reply,
                    conversationId: conversationId
                })

                showMessage('AI分析完成，结果已显示在聊天框中！', 'success')
            } else {
                // 如果没有AI助手，显示成功消息和结果
                showMessage(`AI分析完成！回复：${reply.substring(0, 50)}...`, 'success')
            }
        } else {
            showMessage('AI分析失败，请稍后重试', 'error')
        }
    } catch (error) {
        console.error('划词AI交互失败:', error)
        showMessage('网络连接异常，请检查网络后重试', 'error')
    } finally {
        isProcessing.value = false
        showModeSelector.value = false
        showLanguageSelector.value = false
        selectedSourceLanguage.value = ''
        selectedTargetLanguage.value = ''
        clickListenerEnabled.value = true
    }
}

// 获取模式标题
const getModeTitle = (modeKey) => {
    const mode = modes.find(m => m.key === modeKey)
    return mode ? mode.title : '分析'
}

// 关闭语言选择器
const closeLanguageSelector = () => {
    showLanguageSelector.value = false
    selectedSourceLanguage.value = ''
    selectedTargetLanguage.value = ''
}

// 执行翻译
const executeTranslation = async () => {
    if (!selectedTargetLanguage.value) {
        showMessage('请选择目标语言', 'warning')
        return
    }

    showLanguageSelector.value = false
    await processAiRequest('translate', selectedSourceLanguage.value, selectedTargetLanguage.value)

    // 重置语言选择
    selectedSourceLanguage.value = ''
    selectedTargetLanguage.value = ''
}

// 快速翻译（中英互译）
const quickTranslate = async () => {
    showLanguageSelector.value = false
    await processAiRequest('translate')
}

// 智能定位算法
const calculateOptimalPosition = (selectionRect) => {
    const selectorWidth = 280
    const selectorHeight = showLanguageSelector.value ? 380 : 240
    const margin = 10
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight

    // 定义四个可能的位置
    const positions = [
        // 下方
        {
            left: selectionRect.left,
            top: selectionRect.bottom + margin,
            direction: 'bottom'
        },
        // 上方
        {
            left: selectionRect.left,
            top: selectionRect.top - selectorHeight - margin,
            direction: 'top'
        },
        // 右侧
        {
            left: selectionRect.right + margin,
            top: selectionRect.top,
            direction: 'right'
        },
        // 左侧
        {
            left: selectionRect.left - selectorWidth - margin,
            top: selectionRect.top,
            direction: 'left'
        }
    ]

    // 评估每个位置的适合度
    let bestPosition = null
    let bestScore = -1

    for (const pos of positions) {
        const score = evaluatePosition(pos, selectorWidth, selectorHeight, viewportWidth, viewportHeight, selectionRect)
        if (score > bestScore) {
            bestScore = score
            bestPosition = pos
        }
    }

    // 如果没有找到合适的位置，使用默认位置并调整
    if (!bestPosition || bestScore < 0) {
        bestPosition = {
            left: Math.max(margin, Math.min(selectionRect.left, viewportWidth - selectorWidth - margin)),
            top: Math.max(margin, Math.min(selectionRect.bottom + margin, viewportHeight - selectorHeight - margin)),
            direction: 'bottom'
        }
    }

    // 确保位置在视口内
    bestPosition.left = Math.max(margin, Math.min(bestPosition.left, viewportWidth - selectorWidth - margin))
    bestPosition.top = Math.max(margin, Math.min(bestPosition.top, viewportHeight - selectorHeight - margin))

    return {
        left: bestPosition.left,
        top: bestPosition.top,
        width: selectorWidth
    }
}

// 评估位置适合度
const evaluatePosition = (position, width, height, viewportWidth, viewportHeight, selectionRect) => {
    let score = 0

    // 检查是否在视口内
    if (position.left < 0 || position.top < 0 ||
        position.left + width > viewportWidth ||
        position.top + height > viewportHeight) {
        return -1 // 超出视口
    }

    // 检查是否与选择区域重叠
    const overlap = checkOverlap(
        { left: position.left, top: position.top, width, height },
        { left: selectionRect.left, top: selectionRect.top, width: selectionRect.width, height: selectionRect.height }
    )

    if (overlap) {
        score -= 50 // 重叠扣分
    }

    // 优先级：下方 > 上方 > 右侧 > 左侧
    switch (position.direction) {
        case 'bottom': score += 40; break
        case 'top': score += 30; break
        case 'right': score += 20; break
        case 'left': score += 10; break
    }

    // 距离视口边缘的距离加分
    const distanceFromEdge = Math.min(
        position.left,
        position.top,
        viewportWidth - (position.left + width),
        viewportHeight - (position.top + height)
    )
    score += Math.min(distanceFromEdge, 50)

    return score
}

// 检查两个矩形是否重叠
const checkOverlap = (rect1, rect2) => {
    return !(rect1.left + rect1.width < rect2.left ||
             rect2.left + rect2.width < rect1.left ||
             rect1.top + rect1.height < rect2.top ||
             rect2.top + rect2.height < rect1.top)
}



// 调整语言选择器显示时的位置
const adjustPositionForLanguageSelector = () => {
    const currentLeft = parseInt(selectorStyle.value.left) || 0
    const currentTop = parseInt(selectorStyle.value.top) || 0
    const selectorWidth = parseInt(selectorStyle.value.width) || 280
    const newHeight = 380 // 语言选择器显示时的高度
    const margin = 10

    // 检查是否需要调整位置
    let newLeft = currentLeft
    let newTop = currentTop

    // 检查右边界
    if (currentLeft + selectorWidth > window.innerWidth - margin) {
        newLeft = window.innerWidth - selectorWidth - margin
    }

    // 检查下边界
    if (currentTop + newHeight > window.innerHeight - margin) {
        newTop = window.innerHeight - newHeight - margin
    }

    // 确保不超出上边界和左边界
    newLeft = Math.max(margin, newLeft)
    newTop = Math.max(margin, newTop)

    // 更新位置
    selectorStyle.value = {
        ...selectorStyle.value,
        left: `${newLeft}px`,
        top: `${newTop}px`
    }
}




</script>

<style scoped>
/* 文本截断样式 */
.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

/* 浮层动画 */
.transform {
    transform-origin: top center;
}



/* 浮层阴影优化 */
.shadow-xl {
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 响应式调整 */
@media (max-width: 640px) {
    .absolute {
        max-width: calc(100vw - 20px);
    }
}
</style>
